<template>
  <div class="galaxy-view">
    <div class="galaxy-header">
      <div class="view-title">
        <h1 class="title">
          <span class="title-icon">🌌</span>
          银河系地图
        </h1>
        <p class="subtitle">探索未知星系，发现新的世界</p>
      </div>
      
      <div class="galaxy-controls">
        <div class="zoom-controls">
          <button @click="zoomIn" class="zoom-btn" :disabled="zoomLevel >= maxZoom">
            <span class="btn-icon">🔍</span>
            放大
          </button>
          <span class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</span>
          <button @click="zoomOut" class="zoom-btn" :disabled="zoomLevel <= minZoom">
            <span class="btn-icon">🔍</span>
            缩小
          </button>
        </div>
        
        <div class="view-controls">
          <button @click="centerView" class="control-btn">
            <span class="btn-icon">🎯</span>
            居中
          </button>
          <button @click="toggleGrid" class="control-btn" :class="{ active: showGrid }">
            <span class="btn-icon">⚏</span>
            网格
          </button>
          <button @click="toggleLabels" class="control-btn" :class="{ active: showLabels }">
            <span class="btn-icon">🏷️</span>
            标签
          </button>
        </div>
      </div>
    </div>
    
    <div class="galaxy-content">
      <div class="galaxy-sidebar">
        <div class="sidebar-section">
          <h3 class="section-title">
            <span class="section-icon">📊</span>
            银河统计
          </h3>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">已探索星系</span>
              <span class="stat-value">{{ exploredSystems }}/{{ totalSystems }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">殖民地数量</span>
              <span class="stat-value">{{ colonizedPlanets }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">舰队数量</span>
              <span class="stat-value">{{ fleetCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">探索进度</span>
              <span class="stat-value">{{ Math.round(explorationProgress) }}%</span>
            </div>
          </div>
        </div>
        
        <div class="sidebar-section">
          <h3 class="section-title">
            <span class="section-icon">🎯</span>
            快速导航
          </h3>
          <div class="navigation-list">
            <button 
              v-for="system in importantSystems" 
              :key="system.id"
              @click="focusOnSystem(system)"
              class="nav-item"
            >
              <span class="nav-icon">{{ system.icon }}</span>
              <div class="nav-info">
                <div class="nav-name">{{ system.name }}</div>
                <div class="nav-type">{{ system.type }}</div>
              </div>
            </button>
          </div>
        </div>
        
        <div class="sidebar-section">
          <h3 class="section-title">
            <span class="section-icon">🔍</span>
            搜索星系
          </h3>
          <div class="search-container">
            <input 
              v-model="searchQuery"
              type="text"
              placeholder="输入星系名称..."
              class="search-input"
            >
            <div v-if="searchResults.length > 0" class="search-results">
              <div 
                v-for="result in searchResults" 
                :key="result.id"
                @click="focusOnSystem(result)"
                class="search-result"
              >
                <span class="result-icon">{{ result.icon }}</span>
                <div class="result-info">
                  <div class="result-name">{{ result.name }}</div>
                  <div class="result-distance">距离: {{ result.distance }} 光年</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="galaxy-map-container">
        <div 
          class="galaxy-map" 
          :style="{ 
            transform: `scale(${zoomLevel}) translate(${panX}px, ${panY}px)`,
            cursor: isDragging ? 'grabbing' : 'grab'
          }"
          @mousedown="startDrag"
          @mousemove="drag"
          @mouseup="endDrag"
          @mouseleave="endDrag"
          @wheel="handleWheel"
        >
          <!-- 网格背景 -->
          <div v-if="showGrid" class="galaxy-grid">
            <svg class="grid-svg" width="100%" height="100%">
              <defs>
                <pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
                  <path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>
                </pattern>
              </defs>
              <rect width="100%" height="100%" fill="url(#grid)" />
            </svg>
          </div>
          
          <!-- 星系节点 -->
          <div 
            v-for="system in visibleSystems" 
            :key="system.id"
            class="star-system"
            :class="[
              `system-${system.type}`,
              { 
                explored: system.explored,
                colonized: system.colonized,
                selected: selectedSystem?.id === system.id
              }
            ]"
            :style="{ 
              left: `${system.x}px`, 
              top: `${system.y}px` 
            }"
            @click="selectSystem(system)"
          >
            <div class="system-star" :style="{ backgroundColor: system.color }">
              <div class="star-glow"></div>
            </div>
            
            <div v-if="showLabels && system.explored" class="system-label">
              {{ system.name }}
            </div>
            
            <div v-if="system.colonized" class="colony-indicator">
              <span class="colony-icon">🏠</span>
            </div>
            
            <div v-if="system.hasFleet" class="fleet-indicator">
              <span class="fleet-icon">🚀</span>
            </div>
          </div>
          
          <!-- 航线 -->
          <svg class="trade-routes" width="100%" height="100%">
            <line 
              v-for="route in tradeRoutes"
              :key="route.id"
              :x1="route.from.x + 15"
              :y1="route.from.y + 15"
              :x2="route.to.x + 15"
              :y2="route.to.y + 15"
              stroke="rgba(0, 255, 255, 0.5)"
              stroke-width="2"
              stroke-dasharray="5,5"
            />
          </svg>
        </div>
        
        <!-- 系统详情面板 -->
        <div v-if="selectedSystem" class="system-details">
          <div class="details-header">
            <h3 class="system-name">{{ selectedSystem.name }}</h3>
            <button @click="closeDetails" class="close-details">✕</button>
          </div>
          
          <div class="details-content">
            <div class="system-info">
              <div class="info-item">
                <span class="info-label">星系类型:</span>
                <span class="info-value">{{ selectedSystem.type }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">恒星类型:</span>
                <span class="info-value">{{ selectedSystem.starType }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">行星数量:</span>
                <span class="info-value">{{ selectedSystem.planetCount }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">距离:</span>
                <span class="info-value">{{ selectedSystem.distance }} 光年</span>
              </div>
            </div>
            
            <div class="system-actions">
              <button 
                v-if="!selectedSystem.explored"
                @click="exploreSystem(selectedSystem)"
                class="action-btn primary"
              >
                <span class="btn-icon">🔍</span>
                探索星系
              </button>
              
              <button 
                v-if="selectedSystem.explored && !selectedSystem.colonized"
                @click="colonizeSystem(selectedSystem)"
                class="action-btn success"
              >
                <span class="btn-icon">🏠</span>
                建立殖民地
              </button>
              
              <button 
                v-if="selectedSystem.explored"
                @click="sendFleet(selectedSystem)"
                class="action-btn"
              >
                <span class="btn-icon">🚀</span>
                派遣舰队
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

interface StarSystem {
  id: string
  name: string
  type: 'main' | 'binary' | 'neutron' | 'blackhole' | 'nebula'
  starType: string
  x: number
  y: number
  color: string
  explored: boolean
  colonized: boolean
  planetCount: number
  distance: number
  hasFleet: boolean
  icon: string
}

interface TradeRoute {
  id: string
  from: StarSystem
  to: StarSystem
}

// 响应式数据
const zoomLevel = ref(1)
const minZoom = 0.5
const maxZoom = 3
const panX = ref(0)
const panY = ref(0)
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const showGrid = ref(true)
const showLabels = ref(true)
const selectedSystem = ref<StarSystem | null>(null)
const searchQuery = ref('')

// 模拟数据
const starSystems = ref<StarSystem[]>([
  {
    id: '1',
    name: '太阳系',
    type: 'main',
    starType: 'G型主序星',
    x: 400,
    y: 300,
    color: '#FFD700',
    explored: true,
    colonized: true,
    planetCount: 8,
    distance: 0,
    hasFleet: true,
    icon: '🌟'
  },
  {
    id: '2',
    name: '半人马座α',
    type: 'binary',
    starType: '双星系统',
    x: 450,
    y: 250,
    color: '#FFA500',
    explored: true,
    colonized: false,
    planetCount: 3,
    distance: 4.3,
    hasFleet: false,
    icon: '⭐'
  },
  // 添加更多星系...
])

const tradeRoutes = ref<TradeRoute[]>([])

// 计算属性
const totalSystems = computed(() => starSystems.value.length)
const exploredSystems = computed(() => starSystems.value.filter(s => s.explored).length)
const colonizedPlanets = computed(() => starSystems.value.filter(s => s.colonized).length)
const fleetCount = computed(() => starSystems.value.filter(s => s.hasFleet).length)
const explorationProgress = computed(() => (exploredSystems.value / totalSystems.value) * 100)

const visibleSystems = computed(() => {
  // 根据缩放级别和视口过滤可见星系
  return starSystems.value
})

const importantSystems = computed(() => {
  return starSystems.value
    .filter(s => s.colonized || s.hasFleet)
    .slice(0, 5)
})

const searchResults = computed(() => {
  if (!searchQuery.value) return []
  return starSystems.value
    .filter(s => s.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
    .slice(0, 5)
})

// 方法
function zoomIn() {
  if (zoomLevel.value < maxZoom) {
    zoomLevel.value = Math.min(maxZoom, zoomLevel.value + 0.2)
  }
}

function zoomOut() {
  if (zoomLevel.value > minZoom) {
    zoomLevel.value = Math.max(minZoom, zoomLevel.value - 0.2)
  }
}

function centerView() {
  panX.value = 0
  panY.value = 0
  zoomLevel.value = 1
}

function toggleGrid() {
  showGrid.value = !showGrid.value
}

function toggleLabels() {
  showLabels.value = !showLabels.value
}

function startDrag(event: MouseEvent) {
  isDragging.value = true
  dragStart.value = { x: event.clientX - panX.value, y: event.clientY - panY.value }
}

function drag(event: MouseEvent) {
  if (isDragging.value) {
    panX.value = event.clientX - dragStart.value.x
    panY.value = event.clientY - dragStart.value.y
  }
}

function endDrag() {
  isDragging.value = false
}

function handleWheel(event: WheelEvent) {
  event.preventDefault()
  const delta = event.deltaY > 0 ? -0.1 : 0.1
  const newZoom = Math.max(minZoom, Math.min(maxZoom, zoomLevel.value + delta))
  zoomLevel.value = newZoom
}

function selectSystem(system: StarSystem) {
  selectedSystem.value = system
}

function closeDetails() {
  selectedSystem.value = null
}

function focusOnSystem(system: StarSystem) {
  // 将视图中心移动到指定星系
  panX.value = -system.x + 400
  panY.value = -system.y + 300
  selectedSystem.value = system
}

function exploreSystem(system: StarSystem) {
  // 探索星系逻辑
  system.explored = true
  console.log(`探索星系: ${system.name}`)
}

function colonizeSystem(system: StarSystem) {
  // 殖民星系逻辑
  system.colonized = true
  console.log(`殖民星系: ${system.name}`)
}

function sendFleet(system: StarSystem) {
  // 派遣舰队逻辑
  console.log(`向 ${system.name} 派遣舰队`)
}

// 生命周期
onMounted(() => {
  // 生成更多随机星系
  for (let i = 3; i <= 50; i++) {
    starSystems.value.push({
      id: i.toString(),
      name: `星系-${i}`,
      type: ['main', 'binary', 'neutron', 'blackhole', 'nebula'][Math.floor(Math.random() * 5)] as any,
      starType: ['G型主序星', 'K型主序星', 'M型主序星', '红巨星', '白矮星'][Math.floor(Math.random() * 5)],
      x: Math.random() * 800 + 100,
      y: Math.random() * 600 + 100,
      color: ['#FFD700', '#FFA500', '#FF6B6B', '#4ECDC4', '#45B7D1'][Math.floor(Math.random() * 5)],
      explored: Math.random() > 0.7,
      colonized: Math.random() > 0.9,
      planetCount: Math.floor(Math.random() * 10) + 1,
      distance: Math.random() * 100 + 1,
      hasFleet: Math.random() > 0.8,
      icon: ['🌟', '⭐', '💫', '🌠', '✨'][Math.floor(Math.random() * 5)]
    })
  }
})
</script>

<style scoped>
.galaxy-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%);
  color: var(--text-primary);
  overflow: hidden;
}

.galaxy-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.view-title {
  display: flex;
  flex-direction: column;
}

.title {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
}

.title-icon {
  font-size: 1.5rem;
}

.subtitle {
  margin: 0.25rem 0 0 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.galaxy-controls {
  display: flex;
  gap: 1.5rem;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.zoom-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.2s ease;
}

.zoom-btn:hover:not(:disabled) {
  background: var(--bg-hover);
  border-color: var(--primary-color);
}

.zoom-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.zoom-level {
  font-weight: 600;
  color: var(--primary-color);
  min-width: 50px;
  text-align: center;
}

.view-controls {
  display: flex;
  gap: 0.5rem;
}

.control-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: var(--bg-hover);
}

.control-btn.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.galaxy-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.galaxy-sidebar {
  width: 300px;
  background: var(--bg-secondary);
  border-right: 1px solid var(--border-color);
  overflow-y: auto;
  padding: 1rem;
}

.sidebar-section {
  margin-bottom: 2rem;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 0.75rem;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: var(--bg-primary);
  border-radius: 6px;
  border: 1px solid var(--border-color);
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.stat-value {
  color: var(--primary-color);
  font-weight: 600;
}

.navigation-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
}

.nav-item:hover {
  background: var(--bg-hover);
  border-color: var(--primary-color);
}

.nav-icon {
  font-size: 1.2rem;
}

.nav-info {
  flex: 1;
}

.nav-name {
  font-weight: 600;
  color: var(--text-primary);
}

.nav-type {
  font-size: 0.8rem;
  color: var(--text-secondary);
}

.search-container {
  position: relative;
}

.search-input {
  width: 100%;
  padding: 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
}

.search-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  margin-top: 0.25rem;
  max-height: 200px;
  overflow-y: auto;
  z-index: 10;
}

.search-result {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  cursor: pointer;
  transition: background 0.2s ease;
}

.search-result:hover {
  background: var(--bg-hover);
}

.result-icon {
  font-size: 1.1rem;
}

.result-info {
  flex: 1;
}

.result-name {
  font-weight: 600;
  color: var(--text-primary);
}

.result-distance {
  font-size: 0.8rem;
  color: var(--text-secondary);
}

.galaxy-map-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  background: radial-gradient(ellipse at center, #1a1a2e 0%, #0a0a0a 100%);
}

.galaxy-map {
  position: relative;
  width: 1000px;
  height: 800px;
  transform-origin: center;
  transition: transform 0.1s ease;
}

.galaxy-grid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.grid-svg {
  width: 100%;
  height: 100%;
}

.star-system {
  position: absolute;
  cursor: pointer;
  transition: all 0.2s ease;
}

.star-system:hover {
  transform: scale(1.2);
}

.star-system.selected {
  transform: scale(1.3);
}

.system-star {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  position: relative;
  box-shadow: 0 0 20px currentColor;
}

.star-glow {
  position: absolute;
  top: -5px;
  left: -5px;
  right: -5px;
  bottom: -5px;
  border-radius: 50%;
  background: inherit;
  opacity: 0.3;
  filter: blur(5px);
}

.system-label {
  position: absolute;
  top: 35px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  white-space: nowrap;
  pointer-events: none;
}

.colony-indicator {
  position: absolute;
  top: -5px;
  right: -5px;
  background: var(--success-color);
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
}

.fleet-indicator {
  position: absolute;
  bottom: -5px;
  right: -5px;
  background: var(--primary-color);
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
}

.trade-routes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.system-details {
  position: absolute;
  top: 1rem;
  right: 1rem;
  width: 300px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
}

.details-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  border-bottom: 1px solid var(--border-color);
}

.system-name {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.2rem;
}

.close-details {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-details:hover {
  background: var(--bg-hover);
  color: var(--error-color);
}

.details-content {
  padding: 1rem;
}

.system-info {
  margin-bottom: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid var(--border-color);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.info-value {
  color: var(--text-primary);
  font-weight: 600;
}

.system-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: var(--bg-hover);
}

.action-btn.primary {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.action-btn.success {
  background: var(--success-color);
  color: white;
  border-color: var(--success-color);
}

.btn-icon {
  font-size: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .galaxy-content {
    flex-direction: column;
  }
  
  .galaxy-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }
  
  .system-details {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 90%;
    max-width: 400px;
  }
}
</style>